/**
 * Copyright ©2016-2022 tianyu education Corporation, All Rights Reserved
 * http://www.whty.com.cn/
 */
package profile.hujia.redis.common.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import profile.hujia.redis.dao.model.JedisCommonConfigAttribute;
import profile.hujia.redis.dao.model.JedisPoolConfigAttribute;

import java.time.Duration;

/**
 * class info
 *
 * @author hujia
 * @date 2019-12-24 13:49
 */
@Configuration
public class RedisTemplateConfig {

    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory(JedisPoolConfigAttribute attribute
            , JedisCommonConfigAttribute common) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(attribute.getIp());
        redisStandaloneConfiguration.setPort(attribute.getPort());
        redisStandaloneConfiguration.setPassword(attribute.getPassword());

        LettucePoolingClientConfiguration lettucePoolingClientConfiguration = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofSeconds(2)).poolConfig(genericObjectPoolConfig(common)).build();
        return new LettuceConnectionFactory(redisStandaloneConfiguration, lettucePoolingClientConfiguration);
    }

    @Bean
    public GenericObjectPoolConfig genericObjectPoolConfig(JedisCommonConfigAttribute attribute) {
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxTotal(attribute.getMaxTotal());
        genericObjectPoolConfig.setMinIdle(attribute.getMinIdle());
        genericObjectPoolConfig.setMaxIdle(attribute.getMaxIdle());
        genericObjectPoolConfig.setMaxWaitMillis(attribute.getMaxWaitMillis());
        return genericObjectPoolConfig;
    }

    @Bean("singleRedisTemplate")
    public RedisTemplate<String,String> redisTemplate(JedisPoolConfigAttribute attribute
            , JedisCommonConfigAttribute common){
        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory(attribute,common));
        //序列化策略
        template.setDefaultSerializer(new StringRedisSerializer());
        return template;
    }
}